package com.sgb.kjwl.view.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentCategory3Binding;
import com.sgb.kjwl.di.category.CategoryFragModule;
import com.sgb.kjwl.di.category.DaggerCategoryFragComponent;
import com.sgb.kjwl.view.event.CategoryEvent;
import com.sgb.kjwl.view.event.CategoryEvent2;
import com.sgb.kjwl.view.ui.activity.house.LeaseHallActivity;
import com.sgb.kjwl.view.ui.activity.material.GoodsAggregateActivity;
import com.sgb.kjwl.view.ui.adapter.category.CategoryLeftAdapter;
import com.sgb.kjwl.view.ui.adapter.category.CategoryRightAdapter;
import com.sgb.kjwl.viewmodel.category.CategoryFragModel4;
import com.sgb.knowledgeshare.utils.SharePermissionUtils;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.DialogHelperNew;
import com.swgk.core.event.EventConstant;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.adapter.SectionAdapterOnItemClick;
import com.swgk.core.view.entity.ChannelEntity;
import com.swgk.core.view.entity.MenuEntity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/****
 * 商品分类界面
 * @author Administrator
 */
public class CategoryFragment4 extends AppFragment {
    @Inject
    public CategoryFragModel4 viewModel;
    private FragmentCategory3Binding binding;
    private CategoryLeftAdapter leftAdapter;
    private CategoryRightAdapter rightAdapter;
    private List<MenuEntity<MenuEntity<MenuEntity>>> leftList;
    private List<MenuEntity<MenuEntity>> rightList;
    private List<MenuEntity> data;
    private GridLayoutManager leftManager;
    private int position = 0;
    private int left = 0;
    private List<ChannelEntity> channelEntityList;
    private boolean isShowBar = false;   //用于显示顶部bar
    private String tabName = ""; //首页当前选中的tab栏目

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerCategoryFragComponent.builder()
                .appComponent(appComponent)
                .categoryFragModule(new CategoryFragModule(this))
                .build()
                .inject(this);
    }

    public static CategoryFragment4 newInstance(boolean isActivity, int position) {
        CategoryFragment4 fragment = new CategoryFragment4();
        Bundle bundle = new Bundle();
        bundle.putBoolean("isActivity", isActivity);
        bundle.putInt("type", position);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_category3, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        EventBus.getDefault().register(this);
        initView();
        init();
    }

    private void initView() {
        viewModel.recommendMenu();
        if (leftAdapter == null) {
            leftAdapter = new CategoryLeftAdapter(getActivity(), null);
        }
        setTabLayoutSelentListener();
        isShowBar = getArguments().getBoolean("isActivity");
        int type = getArguments().getInt("type", 0);
        if (type == 1) {
            binding.ivBack.setVisibility(View.GONE);
        } else if (type == 2) {
            binding.ivBack.setVisibility(View.VISIBLE);
            binding.ivBack.setOnClickListener(this);
        }
        leftManager = new GridLayoutManager(getActivity(), 1);
        binding.leftRecycler.setLayoutManager(leftManager);
        binding.leftRecycler.setAdapter(leftAdapter);
//        binding.leftRecycler.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0, getActivity().getResources().getDimension(R.dimen.dp1), getActivity().getResources().getColor(R.color.color_EDEDED)));
        leftAdapter.setItemSelect(true);
        leftAdapter.setOnItemClick(new AdapterOnItemClick<MenuEntity<MenuEntity<MenuEntity>>>() {
            @Override
            public void onItemClick(MenuEntity<MenuEntity<MenuEntity>> menuEntity3MenuEntity3, int position) {
                showRightAdapter(menuEntity3MenuEntity3.getDatas());
                binding.rightRecycler.scrollToPosition(0);
                left = position;
            }
        });
        if (rightAdapter == null) {
            rightAdapter = new CategoryRightAdapter(getActivity(), null);
        }
        binding.rightRecycler.setSectionedRecyclerViewAdapter(rightAdapter);
        binding.rightRecycler.setLoadingMoreEnabled(false);
        binding.rightRecycler.setPullRefreshEnabled(false);
//        SpaceItemDecoration decoration = new SpaceItemDecoration(8);
//        binding.rightRecycler.addItemDecoration(decoration);
        GridLayoutManager rightManager = new GridLayoutManager(getActivity(), 3);
        binding.rightRecycler.setLayoutManager(rightManager);
        binding.rightRecycler.setAdapter(rightAdapter);
        rightAdapter.setOnItemClickListener(new SectionAdapterOnItemClick<MenuEntity>() {
            @Override
            public void onItemClick(MenuEntity menuEntity3, int section, int position) {
                try {
                    if (isShowBar) {
                        Intent intent = new Intent();
                        intent.putExtra("nameId", menuEntity3.getId());//品名
                        if (leftList.get(left).getDatas() != null) {
                            intent.putExtra("threeName", leftList.get(left).getDatas().get(section).getName());
                        }
                        intent.putExtra("threeLevelClassId", menuEntity3.getParentId());//2
                        intent.putExtra("twoLevelClassId", leftList.get(left).getId());//1
                        intent.putExtra("fourLevelClassId", leftList.get(left).getDatas().get(section).getDatas().get(position).getId());//3
                        requireActivity().setResult(Activity.RESULT_OK, intent);
                        requireActivity().finish();
                    } else {
                        if ("租赁".equals(tabName)) {
                            LeaseHallActivity.start(getActivity(), left, section + 1, position + 1);
                        } else {
                            int size = leftList.get(left).getDatas().size();
                            if (leftList.size() > left) {
                                if (size > section) {
                                    List<MenuEntity> datas = leftList.get(left).getDatas().get(section).getDatas();
                                    if (datas.size() > position) {
                                        List<MenuEntity<MenuEntity<MenuEntity>>> menuEntityList = copyMenuEntityList(leftList);
                                        DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.CacheGoodsCategoryModel, reBuildMenuEntity(menuEntityList));
                                        if (data != null) {
//                                            viewModel
                                            viewModel.getIndustryId(leftList.get(left).getId(),menuEntity3.getParentId(),leftList.get(left).getDatas().get(section).getDatas().get(position).getId(),0);
//                                            GoodsAggregateActivity.start(getActivity(), data, 0, leftList.get(left).getId(), menuEntity3.getParentId(), leftList.get(left).getDatas().get(section).getDatas().get(position).getId(), false);
                                        }
                                    }
                                }
                            }

                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @SuppressWarnings("unchecked")
    private <E> List<E> copyMenuEntityList(List<E> src) {
        Type type = new TypeToken<List<MenuEntity<MenuEntity<MenuEntity>>>>() {
        }.getType();
        Object object = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.CachegoryModel, type);
        if (null != object) {
            List<MenuEntity<MenuEntity<MenuEntity>>> cacheList = (List<MenuEntity<MenuEntity<MenuEntity>>>) object;
            if (cacheList.size() > 0) {
                return (List<E>) cacheList;
            }
        }
        return new ArrayList<E>();
    }

    /***
     *修改原数据,每级分类集合数据第一条数据新增“全部”选项
     */
    private List<MenuEntity<MenuEntity<MenuEntity>>> reBuildMenuEntity(List<MenuEntity<MenuEntity<MenuEntity>>> menuEntityList) {

        MenuEntity<MenuEntity<MenuEntity>> children = new MenuEntity<>();
        children.setName("全部");
        children.setId("");
        menuEntityList.add(0, children);

        for (int index0 = 0; index0 < menuEntityList.size(); index0++) {
            List<MenuEntity<MenuEntity>> menuEntityList1 = menuEntityList.get(index0).getDatas();
            if (menuEntityList1 == null) {
                menuEntityList1 = new ArrayList<>();
            }
            MenuEntity<MenuEntity> menuEntity1 = new MenuEntity<>();
            menuEntity1.setName("全部");
            menuEntity1.setId("");
            menuEntityList1.add(0, menuEntity1);
        }

        for (int index0 = 0; index0 < menuEntityList.size(); index0++) {
            List<MenuEntity<MenuEntity>> menuEntityList1 = menuEntityList.get(index0).getDatas();
            if (menuEntityList1 == null) {
                menuEntityList1 = new ArrayList<>();
            }
            for (MenuEntity<MenuEntity> menuEntity : menuEntityList1) {
                List<MenuEntity> menuEntityList2 = menuEntity.getDatas();
                if (menuEntityList2 == null) {
                    menuEntityList2 = new ArrayList<>();
                }
                MenuEntity menuEntity2 = new MenuEntity<>();
                menuEntity2.setName("全部");
                menuEntity2.setId("");
                menuEntityList2.add(0, menuEntity2);
            }
        }
        return menuEntityList;
    }

    private void setTabLayoutSelentListener() {
        Gson gson = new Gson();
        channelEntityList = gson.fromJson(MkvUtils.get().getString(MkvUtils.CommomData, CacheMarker.LocalHomePageTitle, ""), new TypeToken<List<ChannelEntity>>() {
        }.getType());

        ChannelEntity shareChannel =new ChannelEntity();
        shareChannel.setName("直播分享");
        channelEntityList.add(shareChannel);
        binding.classificationTitle.clearOnTabSelectedListeners();
        if (channelEntityList != null && channelEntityList.size() > 0){
            for (int i = 0; i < channelEntityList.size(); i++) {
                String titleName = channelEntityList.get(i).getName();
                if (!"首页推荐".equals(titleName)){
                    if ("首页推荐".equals(titleName)){
                        titleName = "网站推荐";
                    }else if ("商品材料".equals(titleName)){
                        titleName = "销售经营";
                    }
                    binding.classificationTitle.addTab(binding.classificationTitle.newTab().setText(titleName));
                }
            }
        }

        binding.classificationTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //这里就可以根据业务需求处理点击事件了。
                if (tab.getText().toString().contains("分享")) {
                    //知识分享
                    SharePermissionUtils.getPermission(getActivity());
                    return;
                }
                int size = binding.classificationTitle.getSelectedTabPosition();
                int id = channelEntityList.get(size).getId();
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, id));
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                // 点击默认第一个的时候让响应点击事件
                if (tab.getText().toString().contains("分享")) {
                    //知识分享
                    SharePermissionUtils.getPermission(getActivity());
                    return;
                }
                int size = binding.classificationTitle.getSelectedTabPosition();
                int id = channelEntityList.get(size).getId();
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, id));
            }
        });
    }

    private void init() {
        setGridLayoutManager(tabName);
        switch (tabName) {
            case "租赁":
                binding.tabBar.setVisibility(View.GONE);
                break;
            case "会员":
                binding.tabBar.setVisibility(View.GONE);
                break;
            default:
                binding.tabBar.setVisibility(View.VISIBLE);
                break;
        }
    }

    /**
     * 重新设置Ui布局界面显示样式
     *
     * @param name
     */
    public void setGridLayoutManager(String name) {
        this.tabName = name;
        if (binding == null || binding.rightRecycler == null || viewModel == null) {
            return;
        }
        int count = 2;
        if ("租赁".equals(name)) {
            count = 3;
            binding.actionBarTitle.setText("出租分类");
        } else if ("会员".equals(name)) {
            count = 2;
            binding.actionBarTitle.setText("客户分类");
        } else {
            count = 3;
        }
        GridLayoutManager rightManager = new GridLayoutManager(getActivity(), count);
        binding.rightRecycler.setLayoutManager(rightManager);
        binding.rightRecycler.setAdapter(rightAdapter);
        DialogHelperNew.showProgressDialog(getActivity(), "数据加载中...").setCanceledOnTouchOutside(false);
        viewModel.getCategoryModel(name);
    }


    public void setData(List<MenuEntity> data) {
        this.data = data;

    }

    public void showCategoryView(List<MenuEntity<MenuEntity<MenuEntity>>> data) {
        if (data == null || data.size() <= position) {
            return;
        }
        leftList = data;
        leftAdapter.setDatas(data);
        leftAdapter.setDefItem(position);
        leftManager.scrollToPosition(position);
        showRightAdapter(data.get(position).getDatas());
    }

    public void showRightAdapter(List<MenuEntity<MenuEntity>> data) {
        this.rightList = data;
        rightAdapter.setData(data);
        //结束加载动画
        DialogHelperNew.dismissProgressDialog();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(CategoryEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CATEGORY_CHOOSE) {
            position = (int) event.getMessageData();
            if (leftList != null) {
                leftAdapter.setDefItem(position);
                leftManager.scrollToPosition(position);
                showRightAdapter(leftList.get(position).getDatas());
            }
        }
    }

    public void startForResemble(String firstCategoryId, String secondCategoryId, String thirdCategoryId, int position,String hyid){
        GoodsAggregateActivity.start(getActivity(), data, position, firstCategoryId, secondCategoryId, thirdCategoryId, false,hyid);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.iv_back) {
            requireActivity().finish();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}